package com.ktjy.web;

import com.github.pagehelper.PageInfo;
import com.ktjy.entity.Auction;
import com.ktjy.service.AuctionService;
import com.ktjy.service.impl.AuctionServiceImpl;
import com.ktjy.util.RequestUtil;
import my.framework.anno.RequestMapping;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.List;

/**
 * @Author: DABINGCHNEGJIAO
 * @CreateTime: 2025-06-15
 * @Description:
 * @Version: 1.0
 */

public class AuctionControll {

    AuctionService auctionService = new AuctionServiceImpl();

    @RequestMapping("/page")
    public String page(HttpServletRequest request, HttpServletResponse response) {
        String auctionName = request.getParameter("auctionName");
        String auctionDesc = request.getParameter("auctionDesc");
        String auctionStartTime = request.getParameter("auctionStartTime");
        String auctionEndTime = request.getParameter("auctionEndTime");
        String auctionStartPrice = request.getParameter("auctionStartPrice");
        String userIsAdmin = request.getParameter("userIsAdmin");   //判断去管理员页面还是用户页面
        String pageNum = request.getParameter("pageNum");
        String pageSize = request.getParameter("pageSize");
        Auction auction = new Auction();
        auction.setAuctionName(auctionName);
        auction.setAuctionDesc(auctionDesc);
        auction.setAuctionStartTime(auctionStartTime);
        auction.setAuctionEndTime(auctionEndTime);
        auction.setAuctionStartPrice(RequestUtil.parseDouble(auctionStartPrice, 0.0));
        PageInfo<Auction> auctionList = auctionService.selectAuctionuser(auction, RequestUtil.parseInt(pageNum, 1), RequestUtil.parseInt(pageSize, 5));
        if (userIsAdmin == null) {
            userIsAdmin = request.getSession().getAttribute("userIsAdmin").toString();
        }
        request.getSession().setAttribute("auction", auction); //查询条件
        request.getSession().setAttribute("auctionList", auctionList); //分页查询数据
        return userIsAdmin.equals("1") ? "redirect:/auctionList-admin.jsp" : "redirect:/auctionList.jsp";
    }

    @RequestMapping("/save")
    public String save(HttpServletRequest request, HttpServletResponse response) {
        String fileUrl = "";  //图片文件路径
        String fileType = ""; //图片文件类型
        String uploadPath = request.getServletContext().getRealPath("/upload"); // 上传目录
        File uploadDir = new File(uploadPath); // 确保目录存在

        if (!uploadDir.exists()) {
            uploadDir.mkdirs();
        }

        try {
            // 1. 创建文件上传处理器
            DiskFileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);

            // 2. 解析所有字段（包括文件和普通字段）
            List<FileItem> items = upload.parseRequest(request);
            Auction auction = new Auction();

            for (FileItem item : items) {
                if (item.isFormField()) {
                    // 3. 处理普通表单字段
                    String fieldName = item.getFieldName();
                    String value = item.getString("UTF-8"); // 处理中文编码

                    switch (fieldName) {
                        case "auctionId":
                            // 添加空值检查
                            if (value != null && !(value.trim().isEmpty())) {
                                auction.setAuctionId(Long.valueOf(value));
                            }
                            break;
                        case "auctionName":
                            auction.setAuctionName(value);
                            break;
                        case "auctionStartPrice":
                            auction.setAuctionStartPrice(RequestUtil.parseDouble(value, 0.0));
                            break;
                        case "auctionUpset":
                            auction.setAuctionUpset(RequestUtil.parseDouble(value, 0.0));
                            break;
                        case "auctionStartTime":
                            auction.setAuctionStartTime(value);
                            break;
                        case "auctionEndTime":
                            auction.setAuctionEndTime(value);
                            break;
                        case "auctionDesc":
                            auction.setAuctionDesc(value);
                            break;
                    }
                } else {
                    // 4. 处理文件上传
                    if (item.getSize() > 0) { // 确保有文件上传
                        String fileName = item.getName()
                                .replace("..", "")
                                .replaceAll("[\\\\/]", "");

                        File savedFile = new File(uploadDir, fileName);
                        item.write(savedFile);

                        fileUrl = request.getContextPath() + "/upload/" + fileName;
                        fileType = fileName.substring(fileName.lastIndexOf(".") + 1);

                        auction.setAuctionPic(fileUrl);
                        auction.setAuctionPicType(fileType);
                    }
                }
            }

            // 5. 插入数据
            boolean b = auctionService.save(auction);
            request.getSession().removeAttribute("auctionById");
            if (b) {
                return "redirect:/do/page?userIsAdmin=" + request.getSession().getAttribute("userIsAdmin");
            } else {
                return "redirect:/auctionDetail.jsp";
            }

        } catch (Exception e) {
            e.printStackTrace();
            return "redirect:/auctionDetail.jsp";
        }
    }

    //修改
    @RequestMapping("/edit")
    public String edit(HttpServletRequest request, HttpServletResponse response) {
        String auctionId = request.getParameter("auctionId");
        Auction auctionById = auctionService.selectAuctionById(Integer.parseInt(auctionId));
        request.setAttribute("auctionById", auctionById); // 注意key与JSP中取值一致
        return "forward:/auctionDetail.jsp";
    }

    //删除
    @RequestMapping("/delete")
    public String delete(HttpServletRequest request, HttpServletResponse response) {
        String auctionId = request.getParameter("auctionId");
        boolean b = auctionService.deleteAuctionById(Integer.parseInt(auctionId));
        return "redirect:/do/page";
    }
}
